package com.yonder.summary;

import java.util.Calendar;
import java.util.Date;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.yonder.detail.DetailsModel;
import com.yonder.signout.SignOut;

public class Summary extends WebPage {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1012812297018443444L;

	public Summary(PageParameters parameters) {
		super(parameters);
		DetailsModel detailModel = (DetailsModel) getSession().getAttribute("details");

		Label summary = new Label("summaryLbl", String.format(getString("summary"), detailModel.getName(),
				detailModel.getGender(), composeAge(detailModel.getBirthdate()), detailModel.getCity()));
		add(summary);
		add(new Link<Void>("signoutlink") {

			/**
			 * 
			 */
			private static final long serialVersionUID = 6126339323142447511L;

			@Override
			public void onClick() {
				setResponsePage(SignOut.class);
			}

		});
	}

	private String composeAge(Date birthdate) {
		String age = new String();
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());

		Calendar dob = Calendar.getInstance();
		dob.setTime(birthdate);
		Integer years = 0;
		if (dob.after(now)) {
			throw new IllegalArgumentException("Can't be born in the future");
		}
		int year1 = now.get(Calendar.YEAR);
		int year2 = dob.get(Calendar.YEAR);
		years = year1 - year2;
		int month1 = now.get(Calendar.MONTH);
		int month2 = dob.get(Calendar.MONTH);
		if (month2 > month1) {
			years--;
		} else if (month1 == month2) {
			int day1 = now.get(Calendar.DAY_OF_MONTH);
			int day2 = dob.get(Calendar.DAY_OF_MONTH);
			if (day2 > day1) {
				years--;
			}
		}
		if (years < 1) {
			age = "less then one year";
		} else if (years == 1) {
			age = "1 year";
		} else {
			age = years + " years";
		}

		return age;
	}
}
